home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12205 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: mayne.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Is This Bad Coding Practice?
  5. Date: 29 Mar 1996 10:25:32 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4jh9usINNr7p@mayne.ugrad.cs.ubc.ca>
  8. References: <4jgnt2$9d1@loki.tor.hookup.net>
  9. NNTP-Posting-Host: mayne.ugrad.cs.ubc.ca
  10.  
  11. In article <4jgnt2$9d1@loki.tor.hookup.net>,
  12. Rajendra Singh <Rajendra_Singh@msn.com> wrote:
  13.  >int main(int argc, char *argv[])
  14.  >   {
  15.  >   char string[128];
  16.  >   char *func1(void);
  17.  >
  18.  >   strcpy(string, func1());
  19.  >   return 0;
  20.  >   }
  21.  >
  22.  >char *func1(void)
  23.  >   {
  24.  >   char test[100];
  25.  >
  26.  >   sprintf(test, "Test:  %d", 1);
  27.  >   return test;
  28.  >   }
  29.  >
  30.  >... since I am using the value returned from func1() immediately (in
  31.  >main()), is this reliable?  After I copy it into "string", I won't be
  32.  >using that area of memory anymore (i. e. the pointer returned by
  33.  >func1()).
  34.  
  35. Absolutely not. Either malloc the space, or make it static, or allow the caller
  36. to specify storage for the characters:
  37.  
  38.     void func1(char *bufferspace, int size);
  39.  
  40. Otherwise you are relying on the idea that stack frames are being used in a
  41. certain way. It's possible for a C implementation to not use stack frames to
  42. represent activation records. It's even possible that the pointer to test is
  43. completely bound to the activation record, so that it has no de facto meaning
  44. outside of the function.
  45.  
  46. As far as standard C is concerned, the test[] object no longer exists once the
  47. function terminates, and the pointer that was once bound to it is no longer
  48. valid.
  49. -- 
  50.  
  51.